package nin.ja;

import android.os.SystemClock;
import android.util.Log;

public class GameThread implements Runnable{

	private long currentTime;
	private float dt = 1/30; // 30fps
	private RenderQueue renderQueue;
	private GameRenderer renderer;
	private boolean started = false;
	
	private ComponentManager renderManager;
	
	private GameObject player; //temp - for testing
	
	public GameThread(GameRenderer renderer, RenderQueue rq){
		renderQueue = rq;
		this.renderer = renderer;
		
		// temp - for testing
		player = new GameObject();
		//player.addComponent(new RenderComponent(renderSystem, new DrawableObject()));
		renderManager = new ComponentManager();
		renderManager.addComponent(new RenderComponent(renderQueue, player, new DrawableObject()));
		
		currentTime = SystemClock.uptimeMillis();
		Log.v("GameThread" , "GameThread setup complete");
	}
	
	@Override
	public void run() {
		if(!started){
			Log.v("GameThread", "GameThread started!");
			started = true;
		}
		while(true){
			long newTime = SystemClock.uptimeMillis();
			long frameTime = newTime - currentTime;
			Log.v("GameThread", "frameTime: " + frameTime);
			currentTime = newTime;
			while(frameTime > 0.0){
				//renderer.waitDrawingComplete();
				final float deltaTime = frameTime < dt ? frameTime : dt;

				renderManager.update(deltaTime);
				//player.update(deltaTime);
				
				renderQueue.swap(); // Blocks on GameRenderer
				frameTime -= deltaTime;
			}
		}
	}

}
